

 
// 入口函数
/**
 * 
 * @param option 名称，提示，头部信息，头部标题，内容区域
 */
function JsontoExcel(option){
    if(!option){
         throw console.error('option not is empty!'); 
    } 
    this.name = option.name ?? 'index';
    this.tip = option.tip ?? '本插件使用原生HTML对EXCEL模板进行混编构建生成，目前可能存在兼容性，推荐使用WPS预览';
    this.infos = option.infos ?? {company:'暂无',group:'暂无',user:'暂无'};
    this.tHeaders = option.theaders ?? ['负责人','任务1','开始时间','结束时间','状态'];
    this.tBodys  = option.tbodys ?? { 
         
    }; 
    this.author = option.author;
}
// 时间
const getTime = ()=>{
      let date = new Date();
      let y = date.getFullYear();
      let m = date.getMonth()+1;
      let d = date.getDate();
      let h = date.getHours();
      let min = date.getMinutes();
      let s = date.getSeconds();
      return `${y}年${m}月${d}日 ${h}时${min}分${s}秒`
} 
// 迭代器循环
JsontoExcel.prototype.iterator = function(arr,type){ 
   let str = '';
   var eArr = arr[Symbol.iterator]();
   // 浏览器必须支持 for...of 循环
   for (let letter of eArr) { 
        if(type=='header'){
           str+=` <th style="mso-number-format:@">${letter}</th>`
        }else{
           str+=` <td style="mso-number-format:@">${letter}</td>` 
        }
   }
   return str;
}
// 构建模板
/**
 * 
 * @param infos 信息
 * @returns 
 */
const headers = (infos)=>{
      return `
      <th style="height:50px;color:#fff;background:#acb9ca;mso-number-format:@" colspan="3">${infos.company}-${infos.group}</th>
      <th style="height:50px;color:#fff;background:#c6e0b4;mso-number-format:@" colspan="3">主要负责人（组长）:${infos.user}</th> 
      `
}
/**
 * 头部标题
 * @param tipheaders 
 * @returns 
 */ 
const tipHeader = (tipheaders)=>{
      if(!tipheaders.length){
           return false;
      }
      let str = '';
      tipheaders.forEach(item => {
            str+=`<th style="height:50px;color:#fff;background:#92acff;mso-number-format:@">${item}</th>`;
      });  
      return str;
}

/**
 * 内容区域
 * 出入数据格式
 * {
 *       "user1":[
 *              ['b','a','c'],
 *              ['b','a','c']     
 *         ]
 * }
 * @param tipbodys 
 * @returns 
 */
const tipBody = (tipbodys)=>{
        
      let keys = Object.keys(tipbodys); 
      let str = '';
      if(!keys.length) return false;
      const createTb = (list)=>{
            let str1 = ''
            list.forEach((item,indexs)=>{
                  if(indexs==0){
                      str1+=`<td style="background:#8497b0;color:#fff;height:50pt">${item}</td>`
                  }else if(indexs==1){
                      str1+=`<td style="background:#f8cbad">${item.name}</td>`
                  }else if(indexs==2){
                      str1+=`<td style="background:#bdd7ee">${item}</td>` 
                  }else if(indexs==3){
                      str1+=`<td style="background:#bdd7ee">${item}</td>`   
                  }else{
                  
                      if(item=='已完成'){
                        str1+=`<td style="background:#4caf50;color:#fff">已完成✔️</td>` 
                      }else if(item=='进行中'){
                        str1+=`<td style="background:#ffc107;color:#fff">进行中⭕</td>` 
                      }else{
                        str1+=`<td style="background:#dd0a4e;color:#fff">未完成❎</td>`   
                      }
                     
                  }
                  
            })
            
            return str1;
      }
      for(let items of keys){
          tipbodys[items].forEach((item,index)=>{ 
                 if(index==0){
                     str+=`
                     <tr align="center"> 
                     <td  rowspan="${tipbodys[items].length}" style="background:#8497b0;color:#fff;width:100pt;fontWeight:bold;fontSize:16pt">${items}</td> 
                      ${createTb(item)}
                     </tr>
                     `
                 }else{
                  str+=`
                     <tr align="center">  
                     ${createTb(item)}
                     </tr>
                  `
                 }
          })     
      }
      return str;

}

/**
 * 组名称  负责人  
 * 
 * 状态指示
 * 
 * 
 * 
 * 
*  优化目的将excel视图进行更新，人员一对多，开始时间，交付时间，状态
* @returns 模板
*/
JsontoExcel.prototype.template = function() { 

   // if(Array.isArray(this.theader)  && this.theader.length){
   //      theader = this.iterator(this.theader,'header')
   // }
   // if(Array.isArray(this.tbody) && this.tbody.length){
   //      tbody = this.iterator(this.tbody,'body')
   // }
  
   return (
       `  <html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel'><head><!--[if gte mso 9]><xml>
       <x:ExcelWorkbook>
       <x:ExcelWorksheets>
       <x:ExcelWorksheet>
       <x:WorksheetOptions><x:Print><x:ValidPrinterInfo /></x:Print></x:WorksheetOptions>
       </x:ExcelWorksheet>
       </x:ExcelWorksheets>
       </x:ExcelWorkbook></xml><![endif]--> 
       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
       </head><body>
       <table border="1" align="center" cellspacing="1" cellpadding="1">
       
       <tr>  
           ${headers(this.infos)}
       </tr>
       <tr>   
       <th style="height:50px;color:#fff;background:#92acff;mso-number-format:@">提示</th>
       <th style="height:80px;color:#fff;background:#92acff;mso-number-format:@" colspan="5"><p>成功：✔️ 未完成：❎ 进行中：⭕</p>${this.tip}</th> 
       </tr>
       <tr> 
          ${tipHeader(this.tHeaders)} 
       </tr>
         ${tipBody(this.tBodys)}
        <tr style="color:red"> 
            <td>编辑时间</td>
            <td colspan="2">${getTime()}</td>  
            <td>编辑人</td>  
            <td>${this.author}</td>  
        </tr>
       </table>
       </tr> 
       </table></body></html>
      `
   ) 
}




/**
* 下载Excel
*/
JsontoExcel.prototype.download = function() {
   let excel = this.template()
   const blob = new Blob([excel], { type: 'text/html' });
   let url = URL.createObjectURL(blob);
   let Doma = document.createElement('a');
   Doma.setAttribute('download', `${this.name}.xlsx`);
   Doma.setAttribute('href', url);
   Doma.click();  // 触发事件
   Doma.remove(); // 移除本身 
} 
export default JsontoExcel;